/**
 * @author ming
 * @date 2021/2/14 15:44
 * @desc 基础控制器类
 */
package controllers

import (
	"github.com/astaxie/beego"
)

type BaseController struct {
	beego.Controller
	Result ResultMap
}

type ResultMap struct {
	Code    int         `json:"code"`    // 状态码
	Status  bool        `json:"status"`  // 状态
	Message string      `json:"message"` // 错误消息
	Data    interface{} `json:"data"`    // 结果数据
	Debug   string      `json:"-"`       // 调试信息
}

const (
	SuccessCode = 0
	ErrorCode   = -1

	DevMode = "dev"
)

var (
	runMode string = "prod"
)

func init() {
	runMode = beego.AppConfig.String("runMode")
}

func (c *BaseController) SetResult(code int, status bool, msg string, data interface{}, debug string) {
	c.Result.Code = code
	c.Result.Status = status
	c.Result.Message = msg
	c.Result.Data = data
	c.Result.Debug = debug
}

func (c *BaseController) SetResultData(data interface{}) {
	c.Result.Code = SuccessCode
	c.Result.Status = true
	c.Result.Data = data
}

func (c *BaseController) SetError(msg string) {
	c.Result.Code = ErrorCode
	c.Result.Status = false
	c.Result.Message = msg
}

func (c *BaseController) SetCode(code int) {
	c.Result.Code = code
}

func (c *BaseController) SetErrorWithDebug(msg string, debug string) {
	c.Result.Code = ErrorCode
	c.Result.Status = false
	c.Result.Message = msg
	c.Result.Debug = debug
}

func (c *BaseController) SetErrorWithCode(msg string, code int) {
	c.Result.Code = code
	c.Result.Status = false
	c.Result.Message = msg
}

func (c *BaseController) Finish() {
	w := c.Ctx.ResponseWriter
	w.Header().Add("Access-Control-Allow-Origin", "*")
	w.Header().Add("Access-Control-Max-Age", "1800")

	if runMode == DevMode && c.Result.Debug != "" {
		c.Result.Message = "err:" + c.Result.Message + " debug:" + c.Result.Debug
	}

	c.SetData(c.Result)
	c.ServeJSON()
}
